<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title>直播间</title>
    <link rel="stylesheet" href="__CSS__/css.css?2"/>
    <script src="__JS__/jquery-2.1.0.js"></script>
</head>
<body class="hide">

<div id="video">

</div>

<script src="//cdn.ronghub.com/RongIMLib-2.3.3.min.js"></script>
<script src="/public/admin/js/layer/layer.js?{$stamp}"></script>
</body>
<script>




//
// //发送消息框
$('#talk').keydown(function(event) {

    if (event.keyCode == 13) {

        if (ban == 'ban'){
           return false;
        }else {
            send();

        }

    }
});
    //浮动层删除
    $(document).on("click",".send",function() {

        console.log('in');
        if (ban == 'ban'){
            return false;
        }else {
            send();

        }

    });

function send() {
    var str = $("#talk").val();

    if (!str){
        console.log('无文字');
        return false;
    }

    var extra = new Object();
    extra.role_id = "{$data.role_id}";
    extra.nick_name = "{$data.nick_name}";
    extra.header_img = "{$data.header_img}";
    var msg = new RongIMLib.TextMessage({
        content: escapeJquery(str),
        extra:JSON.stringify(extra),
    });
    $("#talk").val('');
    sendMessage(msg);
}

//去除标签
function escapeJquery(srcString) {
    var escapseResult = srcString;

    var reg = new RegExp("<[^<]*>", "gi");
    escapseResult = escapseResult.replace(reg, "");
    // console.log(escapseResult)
    return escapseResult;
};

    $(function(){
        $('#pb').click(function(){
            var id = $(this).attr('data-id');
            if(id == 0){
                $('.q').show();
                $(this).attr('data-id',1);
            }else{
                $('.q').hide();
                $(this).attr('data-id',0);
            }

        })

        var he = $('body').innerHeight()-$('.video').innerHeight()-46;
        $('.room').css({height:he+'px'});
        $('.room-zb').css({height:he+50+'px'});
        var video = document.getElementById('video');

    });
    $('.video-list p').click(function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');
        var type = "#"+$(this).attr('data-type');
        $('.room-n').hide();
        $(type).show();
//        switch (type){
//            case 'lt': $('#lt').show(); break;
//            case 'zb': $('#zb').show(); break;
//            case 'hf': $('#hf').show(); break;
//            case 'cy': $('#cy').show(); break;
//        }
    })
    $('.fxa').click(function(){
        $('.meng').show();
    })
    $('.off').click(function(){
        $('.meng').hide();
    });

    var params = {
        appKey :"{:config('rongyun.appKey')}",
        token : "BAeT9mMtRIlQJAgTMAkODIhetdjBa/HCN6Rszg1XFnxNrfLes5FdQG3Pe6svQqsnLhxM61wl9BbrdE/LpYEAjV1IA+nRnWra",
    };
    var callbacks = {

    };

    init(params,callbacks);
    var messageName = "UnkownMessage"; // 消息名称。
    var objectName = "RC:Chatroom:Welcome"; // 消息内置名称，请按照此格式命名。
    var mesasgeTag = new RongIMLib.MessageTag(true,true);// 消息是否保存是否计数，true true 保存且计数，false false 不保存不计数。
    var prototypes = ["name","age"]; // 消息类中的属性名。
    RongIMClient.registerMessageType(messageName,objectName,mesasgeTag,prototypes);
    // RongIMLib.RongIMClient.init('m7ua80gbmjrnm');
    // var token = "{$data.r_token}";
    function init(params, callbacks, modules){
        var appKey = params.appKey;
        var token = params.token;
        var navi = params.navi || "";

        modules = modules || {};
        var RongIMLib = modules.RongIMLib || window.RongIMLib;
        var RongIMClient = RongIMLib.RongIMClient;
        var protobuf = modules.protobuf || null;

        var config = {};

        //私有云切换navi导航，私有云格式 '120.92.10.214:8888'
        if(navi !== ""){
            config.navi = navi;
        }

        //私有云切换api,私有云格式 '172.20.210.38:81:8888'
        var api = params.api || "";
        if(api !== ""){
            config.api = api;
        }

        //support protobuf url + function
        if(protobuf != null){
            config.protobuf = protobuf;
        };


        RongIMLib.RongIMClient.init(appKey,null,config);

        //
        // /*
        //  文档：http://www.rongcloud.cn/docs/web.html#3、设置消息监听器
        //
        //  注意事项：
        //  1：为了看到接收效果，需要另外一个用户向本用户发消息
        //  2：判断会话唯一性 ：conversationType + targetId
        //  3：显示消息在页面前，需要判断是否属于当前会话，避免消息错乱。
        //  4：消息体属性说明可参考：http://rongcloud.cn/docs/api/js/index.html
        //  */


        var instance = RongIMClient.getInstance();

        // 连接状态监听器
        RongIMClient.setConnectionStatusListener({
            onChanged: function (status) {

                // console.log(status);
                switch (status) {
                    case RongIMLib.ConnectionStatus["CONNECTED"]:
                    case 0:
                        console.log("连接成功")
                        callbacks.getInstance && callbacks.getInstance(instance);
                        break;

                    case RongIMLib.ConnectionStatus["CONNECTING"]:
                    case 1:
                        console.log("连接中")
                        break;

                    case RongIMLib.ConnectionStatus["DISCONNECTED"]:
                    case 2:
                        console.log("当前用户主动断开链接")
                        break;

                    case RongIMLib.ConnectionStatus["NETWORK_UNAVAILABLE"]:
                    case 3:
                        console.log("网络不可用")
                        break;

                    case RongIMLib.ConnectionStatus["CONNECTION_CLOSED"]:
                    case 4:
                        console.log("未知原因，连接关闭")
                        break;

                    case RongIMLib.ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"]:
                    case 6:
                        console.log("用户账户在其他设备登录，本机会被踢掉线")
                        break;

                    case RongIMLib.ConnectionStatus["DOMAIN_INCORRECT"]:
                    case 12:
                        console.log("当前运行域名错误，请检查安全域名配置")
                        break;
                }
            }
        });



        //开始链接
        var userid;
        var chatRoomId = "1"; // 聊天室 Id。
        console.log(chatRoomId);
        console.log('test');
        RongIMClient.connect(token, {
            onSuccess: function(userId) {
                callbacks.getCurrentUser && callbacks.getCurrentUser({userId:userId});
                console.log("链接成功，用户id：" + userId);
                userid=userId;
                var conversationtype = RongIMLib.ConversationType.CHATROOM;
                var count =0;
                RongIMClient.getInstance().joinChatRoom(chatRoomId, count, {
                    onSuccess: function() {
                        console.log(chatRoomId);
                        // 加入聊天室成功。
                        console.log('加入聊天室成功。');

                        var order = RongIMLib.GetChatRoomType.REVERSE;// 排序方式。
                        RongIMClient.getInstance().getChatRoomInfo(chatRoomId, count, order, {
                            onSuccess: function(chatRoom) {
                                // chatRoom => 聊天室信息。
                                // chatRoom.userInfos => 返回聊天室成员。
                                // chatRoom.userTotalNums => 当前聊天室总人数。
                                console.log(chatRoom.userInfos);
                                console.log(chatRoom.userTotalNums);
                            },

                            onError: function(error) {
                                // 获取聊天室信息失败。
                            }
                        });
                    },
                    onError: function(error) {
                        // 加入聊天室失败
                        console.log('加入聊天室失败。');
                    }
                });
                // sendMessage('xxxx',chatRoomId);

            },
            onTokenIncorrect: function() {
                console.log('token无效');
            },
            onError:function(errorCode){
                console.log(errorCode);
            }
        });}

// 发送消息相关参数说明
var conversationtype = RongIMLib.ConversationType.CHATROOM;
/*
PRIVATE 为单聊、
GROUP 为群组、
CHATROOM 为聊天室、
CUSTOMER_SERVICE 为客服、
SYSTEM 为系统消息、
APP_PUBLIC_SERVICE 为应用公众账号（应用内私有）、
PUBLIC_SERVICE 为公众账号 (公有)
*/

var targetId = "{$data.chat_id_play}"; // 目标 Id，根据不同的 ConversationType，可能是用户 Id、群组 Id。

    function sendMessage(msg) {

        RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
            // 发送消息成功
            onSuccess: function (message) {
                var extra = eval('(' + message.content.extra + ')');
                var str = '<p><span>'+extra.nick_name+'：</span>'+message.content.content+'</p>';
                $('.room-txt').append(str);
                console.log($('.room-txt')[0].scrollHeight);
                $('.room').scrollTop($('.room')[0].scrollHeight);
                // getMessage();
                console.log(message)
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                // console.log("Send successfully");
            },
            onError: function (errorCode, message) {
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default:
                        info = "x";
                        break;
                }
                console.log('发送失败:' + info);
            }
        });
    }
    // function getMessage() {
    RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: function(message) {

            // 判断消息类型
            console.log('messageContent:');

            console.log(message);

            switch (message.messageType) {
                case RongIMClient.MessageType.TextMessage:


                    var extra = eval('(' + message.content.extra + ')');

                    if (message.senderUserId == 'sys'){
                        if (message.content.content == '开放聊天中~'){

                            $("input[name='msg']").attr('placeholder',"吐个槽吧~");
                            $("input[name='msg']").removeAttr("readonly");
                            $('.btn').addClass('send');
                            ban = 'on';

                        }else{
                            $("input[name='msg']").attr('placeholder',"全员禁言中~");
                            $("input[name='msg']").attr("readonly","readonly");
                            ban = 'ban';
                            $('.btn').removeClass('send');
                        }
                        var str = '<p style="color: red"><span style="color: red" >'+extra.nick_name+'：</span>'+message.content.content+'</p>';
                    }else{
                        var str = '<p ><span >'+extra.nick_name+'：</span>'+message.content.content+'</p>';
                    }
                    
                    





                    $('.room-txt').append(str);
                    $('.room').scrollTop($('.room')[0].scrollHeight);
                    // answers(message.content.content,message.senderUserId);
                    break;
                case RongIMClient.MessageType.ImageMessage:

                    // do something...
                    break;
                case RongIMClient.MessageType.DiscussionNotificationMessage:

                    // do something...
                    break;
                case RongIMClient.MessageType.LocationMessage:

                    // do something...
                    break;
                case RongIMClient.MessageType.RichContentMessage:

                    // do something...
                    break;
                case RongIMClient.MessageType.DiscussionNotificationMessage:

                    // do something...
                    break;
                case RongIMClient.MessageType.InformationNotificationMessage:
                    // do something...
                    break;
                case RongIMClient.MessageType.ContactNotificationMessage:
                    // do something...
                    break;
                case RongIMClient.MessageType.ProfileNotificationMessage:
                    // do something...
                    break;
                case RongIMClient.MessageType.CommandNotificationMessage:
                    // do something...
                    break;
                case RongIMClient.MessageType.CommandMessage:
                    // do something...
                    break;
                case RongIMClient.MessageType.UnknownMessage:
                    if(status == 1){
                        if(message. senderUserId== 'system'){
                            if(message.content.message.content.content.type == 'gift' ){
                                if ((gift_status != 1)) return false;
                                var st = '';
                                for(var i=0;i<message.content.message.content.content.data.num.length;i++){
                                    st += '<img src="__IMG2__/'+message.content.message.content.content.data.num[i]+'.png"/>';
                                }
                                var str = '<p class="padding_10"><img class="bg_gife" style="width: 36px;" src="'+message.content.message.content.content.data.img+'"/><img  src="__IMG2__/x.png"/>'+st+'</p>';
                                $(".gife").html(str);
                                $(".gife").css('display','block');
                                $('.gife').addClass('animated slideInRight');
                                setTimeout(function(){
                                    $('.gife').removeClass('slideInRight');

                                }, 1000);
                                $('.gife').delay(1000).fadeOut(200);
                                return false;
                            }else if(message.content.message.content.content.type == 'red_package'){
                                if ((system_status != 1)) return false;
                                var str = '<p class="live-msg mg_top10"><i class="xi">系</i>'+message.content.message.content.content.data.role_name+'发出了一个红包 <img class="vertical-align_m" id="red" src="__IMG2__/msg_redbag.png" alt=""  onclick="getredPackage(this)" data-id="'+message.content.message.content.content.data.red_id+'" data-name="'+message.content.message.content.content.data.role_name+'" data-type="'+message.content.message.content.content.data.red_type+'" data-img="'+message.content.message.content.content.data.header_img+'"/></p>';
                            }else if(message.content.message.content.content.type == 'guess'){
                                if ((system_status != 1)) return false;
                                var str = '<p class="live-msg mg_top10"><i class="xi">系</i><span class="green">房主发起了一次竞猜</span><img class="vertical-align_m" src="__IMG2__/msg_tv.png" alt="" /></p>';
                            }else if(message.content.message.content.content.type == 'system'){
                                if ((system_status != 1)) return false;
                                var str = '<p class="live-msg mg_top10"><i class="xi">系</i><span class="green">'+message.content.message.content.content.data+'</span><img class="vertical-align_m" src="__IMG2__/msg_tv.png" alt="" /></p>';

                            }else{

                            }
                            $(".room-txt").append(str);
                        }
                    }else {
                        if (message.senderUserId == 'system') {
                            if (message.content.message.content.content.type == 'gift') {
                                var str = '<div class="gife"><p class="padding_10"><img class="bg_gife" src="' + message.content.message.content.content.data.img + '"/><img  src="__IMG2__/x.png"/><img src="__IMG2__/2.png"/></p></div>'
                            } else if (message.content.message.content.content.type == 'red_package') {
                                if(message.content.message.content.content.data.role_id == '{$info.role_id}'){
                                    var str = '<div class="padding_10 mg_top10"><div class="clearfix text-center"><dl class="clearfix left width_100"><dt class="right"><img class="head" src="'+message.content.message.content.content.data.header_img+'"></dt><dd class="right padding_lr10"><div class="red-bag" onclick="getredPackage(this)" data-id="'+message.content.message.content.content.data.red_id+'" data-name="'+message.content.message.content.content.data.role_name+'" data-type="'+message.content.message.content.content.data.red_type+'" data-img="'+message.content.message.content.content.data.header_img+'" style="width: 200px;height: 70px;background: url(__IMG2__/redpackage-right.png)no-repeat;background-size:100% 100% ;position: relative;"><p class="color_ff redfont" style="margin: 0px 0 0 45px;padding-top: 10px;width: 150px;text-align: left;">'+message.content.message.content.content.data.msg+'</p><p class="color_ff redfont" style="margin: 0px 0 0 45px;font-size: 0.5rem;width: 150px;text-align: left;">查看红包</p><p class="redtext" style="position: absolute;bottom: 0px;left: 5px;font-size: 12px;color: #a9a9a9;">聊天室红包</p></div></dd></dl></div></div>';
                                }else{
                                    var str = '<div class="padding_10 mg_top10"><div class="clearfix text-center"><dl class="clearfix left width_100"><dt class="left"><img class="head" src="'+message.content.message.content.content.data.header_img+'"></dt><dd class="left padding_lr10"><div class="red-bag left_redbag"  onclick="getredPackage(this)" data-id="'+message.content.message.content.content.data.red_id+'" data-name="'+message.content.message.content.content.data.role_name+'" data-type="'+message.content.message.content.content.data.red_type+'" data-img="'+message.content.message.content.content.data.header_img+'" style="width: 200px;height: 70px;background: url(__IMG2__/redpackage-left.png)no-repeat;position: relative;background-size:100% 100% ;"><p class="color_ff redfont" style="margin: 0px 0 0 45px;padding-top: 10px;width: 150px;text-align: left;">'+message.content.message.content.content.data.msg+'</p><p class="color_ff redfont" style="margin: 0px 0 0 45px;font-size: 0.5rem;width: 150px;text-align: left;">查看红包</p><p class="redtext" style="position: absolute;bottom: 0px;left: 5px;font-size: 12px;color: #a9a9a9;">聊天室红包</p></div></dd></dl></div></div>';
                                }
                            } else if (message.content.message.content.content.type == 'guess') {
                                var str = '<p class="live-msg mg_top10"><i class="xi">系</i>' + message.content.message.content.content.data.role_name + '发出了一个红包 <img class="vertical-align_m" id="red" src="__IMG2__/msg_redbag.png" alt="" /></p>';
                            } else if (message.content.message.content.content.type == 'system') {
                                var str = '<p><span>' + message.senderUserId + '：</span>' + message.content.content + '</p>';
                            } else {

                            }
                            $(".room-txt").append(str);
                        }
                    }

                    //console.log('xxxxx');
                    // do something...
                    break;
                case RongIMClient.MessageType.VoiceMessage:
                    // //console.log(message);
                    // getVoice((message.content.duration), (message.content.content));

                    break;
                case RongIMClient.MessageType.PersonMessage:
                    // //console.log(message);
                    // getVoice((message.content.duration), (message.content.content));
                    var extra = eval('(' + message.content.extra + ')');
                    // var extra = message.content.extra;

                    var str = '<p class="live-msg mg_top10"><i class="xi">系</i><span class="blue">'+extra.nick_name+'</span> 进入直播间<img class="vertical-align_m" src="__IMG2__/msg_hores.png" alt="" /></p>';
                    $('.room-txt').append(str);
                    break;
                default:
                //console.log(message);

                // 自定义消息
                // do something...
            }
        }
    });
    // }
    console.log("{$data.role_id}");
    console.log('role_id');
$("#send").click(function () {

});
    function order(that) {
        var html =$(that).html();
        var id = $(that).data('id');
        var form = new FormData();
        form.append('id',id);

        if(html == '预定'){
            var result = httpPosts('/Play/reserve',form);
            if(result == null){
                $(that).css('background','#d9d9d9');
                $(that).css('color','#7f7f7f');
                $(that).html('已预定');
            }
        }else if(html == '已预定'){
            var result = httpPosts('/Play/reserve',form);
            if(result == null){
                $(that).css('background','#2e89fe');
                $(that).css('color','#fff');
                $(that).html('预定');
            }
        }
    }
$("#look").click(function () {
    var html = $(this).html();
    var num = $('.r').children('b').html();
    if(html == '关注'){
        var formDatas = new FormData();
        formDatas.append('role_id','{$data.Homeowner}');
        var result = httpPosts('/Focus/addFocusRole',formDatas);
        // console.log(result);
        if(result == null){
            $('.r').children('a').css('background','#d9d9d9');
            $('.r').children('a').css('color','#7f7f7f');
            $('.r').children('a').html('已关注');
            num++;
            $('.r').children('b').html(num);
        }
    }else{
        var formDatas = new FormData();
        formDatas.append('role_id','{$data.Homeowner}');
        var result = httpPosts('/Focus/hiddenRole',formDatas);
        // console.log(result);
        if(result == null){
            $('.r').children('a').css('background','#2e89fe');
            $('.r').children('a').css('color','#fff');
            $('.r').children('a').html('关注');
            num--;
            $('.r').children('b').html(num);
        }
    }
});
     function load(that) {
         var forms = new FormData();
         var page = $(that).data('this-page');
         var id = $(that).data('id');
         page++;
         forms.append('page',page);
         forms.append('id',id);
         var people_list = httpPosts('/play/roomUsers',forms);
         var str = '';
         $(that).css('display','none');
         for(var i=0;i<people_list.data.length;i++){
             str += ' <li><img src="'+people_list["data"][i]["header_img"]+'" alt=""/><p><span class="ti">'+people_list["data"][i]["role_name"]+'</span><span><a class="blue">'+people_list["data"][i]["remark"]+'</a></span></p><b class="both"></b></li>';
         }
         if(people_list["hasNext"]){
             str += '<button class="loading" onclick="load(this)" data-id="{$data.room_id}" data-thispage="'+page+'" data-hasnext="1" style="width: 100%;height: 3rem;background-image: -webkit-linear-gradient(top, #ccc, #eee);border: 1px solid #eee;">点击加载更多</button>';
         }
         $("#peoples").children('ul').append(str);
    }
//


    function  jump() {
        layer.confirm('即将离开页面？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            location.href = '{:url(login/login)}';
        }, function(){

        });
    }
</script>
</html>